#encoding=utf8
'''
Created on Apr 14, 2015

@author: jingyang <jingyang@smalltreemedia.com>
'''
from django.http.response import Http404, HttpResponse

from notification.models import Notice, ReportReceiver
from utils import JsonResponse, this_week
from HTMLParser import HTMLParser
from django.shortcuts import render_to_response
from django.template.context import Context
import datetime
from core.admin_site import get_context
from app_info.models import AppVersion
from django.template.loader import get_template
from django.core.mail.message import EmailMessage, EmailMultiAlternatives
import settings


class MLStripper(HTMLParser):
    def __init__(self):
        self.reset()
        self.fed = []

    def handle_data(self, d):
        self.fed.append(d)

    def get_data(self):
        return ''.join(self.fed)


def strip_tags(html):
    s = MLStripper()
    s.feed(html)
    return s.get_data()


def get_unread_notices(req):
    if not req.is_ajax():
        raise Http404
    if not req.user.is_authenticated():
        return JsonResponse({'status': -1})
    notice = Notice.objects.filter(read=False, showed=False, receiver=req.user)[:1]
    count = Notice.objects.filter(read=False, receiver=req.user).count()
    if notice:
        notice = notice[0]
        rtn = {'sender': notice.sender.username if notice.sender else 'system',
            'subject': strip_tags(notice.subject), 'create_time': notice.create_time,
            'status': 1, 'nid': notice.pk, 'count': count,
            'callback': '/admin/notification/notice/%s/' % notice.pk}
        notice.showed = True
        notice.save()
    else:
        rtn = {'status': 0}
    return JsonResponse(rtn)


def weekly_report(req):
    today = datetime.date.today()
    date = today - datetime.timedelta(days=7)
    monday, sunday = this_week(date)
    if settings.DEBUG:
        domain = 'localhost:8000'
    else:
        if settings.STAGING:
            domain = 'pts.stm.com'
        else:
            domain = 'pts.mokitech.com'
    ctx = {'monday': monday, 'sunday': sunday, 'domain': domain}
    ctx.update(get_context())

    metrics = []

    for n, label in enumerate(['Apps Released In Last Week',
        'Apps Submitted In Last Week', 'Apps In Review']):
        if n == 0:
            data = AppVersion.objects.filter(status='L', date_released__range=(monday, sunday))
        elif n == 1:
            data = AppVersion.objects.filter(status__in=['S', 'L'], date_submitted__range=(monday, sunday))
        else:
            data = AppVersion.objects.filter(status='S')
        metrics.append({'label': label, 'count': data.count(), 'data': data})

    ctx.update({'data_group': metrics})
    return render_to_response('base/weekly_email.html', Context(ctx))

    t = get_template('base/weekly_email.html')
    for r in ReportReceiver.objects.filter(is_active=True):
        ctx.update({'r': r})
        html = t.render(Context(ctx))
        msg = EmailMessage('Weekly Report', html, settings.EMAIL_HOST_USER, [r.email])
        msg.content_subtype = 'html'
        msg.send()
    return HttpResponse('Done')
